package wwl.lsf.hellospringboot.test.nio.简单的聊天;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import org.apache.commons.lang3.StringUtils;

public class ChatClient {

  private String ip = "127.0.0.1";
  private Integer port = 9999;

  private SocketChannel socketChannel;

  private String userName;

  public ChatClient() throws Exception {

    socketChannel = SocketChannel.open();

    socketChannel.configureBlocking(false);

    InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, port);
    if (!socketChannel.connect(inetSocketAddress)) {
      while (!socketChannel.finishConnect()) {  //nio作为非阻塞式的优势
        System.out.println("Client:连接服务器端的同时，我还可以干别的一些事情");
      }

    }

    userName = socketChannel.getLocalAddress().toString();
    System.out.println("客户端" + userName + "已经就绪了");
  }

  public void sendMsg(String msg) throws IOException {

    if (StringUtils.equalsIgnoreCase(msg, "bye")) {
      socketChannel.close();
      socketChannel = null;
      return;
    }
    msg = userName + "说:" + msg;
    socketChannel.write(ByteBuffer.wrap(msg.getBytes()));

  }

  public void receiveMsg() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

    try {
      int read = socketChannel.read(byteBuffer);

      if (read > 0) {
        System.out.println(new String(byteBuffer.array()));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }


}
